package ex1;
import java.io.*;
import java.net.*;

/* This is the server side of the UDP example
   It waits for a connection request from a client, reads a line
   from the socket, converts that string to upper case and then
   sends it back.  It then waits for another connection
*/

class UDPServer {
    public static void main (String args[])
      throws Exception
      /* if you have time at the end take a look at the exceptions that might be raised and think about nicer ways of handling them */
      {
	String 		clientSentence;
	String 		capitalisedSentence;
        byte[] 		sendData, receiveData;

        /* prepare the socket and data arrays */
	DatagramSocket serverSocket = new DatagramSocket(4321);
        receiveData = new byte[1024];
        sendData = new byte[1024];

	while (true) {
        	// set up an empty packet to recieve into
		DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);

                // actually get something from the socket
		serverSocket.receive(receivePacket);
		clientSentence = new String(receivePacket.getData());

                // get the sender's address to send the response to
                InetAddress clientIPAddress = receivePacket.getAddress();
                int clientPort = receivePacket.getPort();

		// modify the data
		capitalisedSentence = clientSentence.toUpperCase();

                // prepare the packet to send back
                sendData = capitalisedSentence.getBytes();
		DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, clientIPAddress, clientPort);

                // and now send the packet to the client
		serverSocket.send(sendPacket);

                // again, it would be better to tidy up after ourselves here ... maybe you can add this if you have time at the end!
 	}
}
}
